"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/11/6
 */
import * as React from 'react'
import {autoSize, commonStyles} from "../../assets/styles/common";
import MyText from "../../component/MyText";
import {activeStyles, filterButton, noActiveStyles} from "../../assets/styles/community";
import MyIcon from "../../component/icon";

import {activeList} from "../../assets/data";
import Line from "../../component/Line";
import Avatar from "../../component/Avatar";
import {groupStyles} from "../../assets/styles/groups";
import {ActivePage} from "../../interface/router";
import constant from "../../utils/constant";
import Request from "../../utils/Request";

const {View, DeviceEventEmitter, TouchableOpacity, FlatList} = require('react-native');
const {List} = require('antd-mobile');
const {connect} = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
const {Actions} = require("react-native-router-flux");
const moment = require("moment");

//无活动页面
const NoActive = () => (
    (
        <View style={[commonStyles.container, {padding: 10}]}>
            <View style={[commonStyles.centerVH, noActiveStyles.container]}>
                <View style={[commonStyles.centerVH, noActiveStyles.iconContainer]}>
                    <MyIcon name={'icon-weizhaodaoshuju'} color='#252729' size={40}/>
                </View>
                <MyText color='#666'
                        fontSize={15}
                        style={{marginTop: 15}}>未找到活动。尝试清理过滤器，以获取更多结果。</MyText>
            </View>
        </View>
    )
);


const avatarProps = {
    borderWidth: 1,
    borderColor: '#fff',
    size: 35,
};

class ActiveList extends React.Component<ActivePage, any> {


    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            activeList: [],
            typeList: [],
        };

    }


    componentDidMount(): void {

        DeviceEventEmitter.addListener(constant.noticeKeyOfEnterActiveList, this.onRefresh)

    }

    componentWillUnmount(): void {
        DeviceEventEmitter.removeListener(constant.noticeKeyOfEnterActiveList);
    }


    onRefresh = () => {
        this.props.dispatch({
            type: 'active/fetchUserActiveList'
        });
        if (this.props.active.selectedActiveTypes.length > 0) {
            this.props.dispatch({
                type: 'active/fetchList',
                payload: {pi: 1, ps: 10, ids: this.props.active.selectedActiveTypes.join(',')}
            })
        } else {
            this.props.dispatch({
                type: 'active/clear',
            })
        }
    };

    //应用筛选
    onApply = (typeList) => {
        // if (typeList.length > 0) {
        //     this.setState({typeList});
        //     this.props.dispatch({
        //         type: 'active/fetchList',
        //         payload: {pi: 1, ps: 10, ids: typeList.join(',')}
        //     })
        // } else {
        //     this.props.dispatch({
        //         type: 'active/clear'
        //     })
        // }
    };

    joinOrLeaveActive = (active: activity) => {
        this.props.dispatch({
            type: 'active/joinOrLeaveActive',
            payload: {active}
        });
        // this.props.dispatch({
        //     type: 'active/fetchList',
        //     payload: {pi: 1, ps: 10, ids:this.state.typeList.join(',')}
        // })
    };

    goToDetail = (activeDetail) => {
        // Actions.activeDetail({})

        this.props.dispatch({
            type: 'active/goToDetail',
            payload: {
                activeDetail
            }
        })
    };


    renderMembers = (members: userItem[]) => {

        if (!(members && members.length > 0)) return null;

        let m = [];
        let index = 0;
        m.push(<Avatar key={index++} {...avatarProps}
                       content={<MyText color={'white'}>{`+${members.length}`}</MyText>}
                       style={[groupStyles.member, {zIndex: 8 - (index * 2), backgroundColor: '#DC6451'}]}
        />);
        members.map((item: userItem, i) => {
            if (index < 4) {
                m.push(<Avatar key={index++} {...avatarProps}
                               style={[groupStyles.member, {zIndex: 8 - (index * 2), backgroundColor: '#DC6451'}]}
                               source={{uri: Request.checkImageUrl(item.avatar)}}/>);
            }
        });
        return m;
    };

    renderListHeaderComponent = () => {
        if (!this.props.active.userJoinedActiveList || this.props.active.userJoinedActiveList.length <= 0) {
            return null;
        }
        return (
            <List>
                <List.Item arrow='horizontal'
                           onClick={Actions.myActives}>{`正在参加${this.props.active.userJoinedActiveList.length}活动`}</List.Item>
                {this.props.active.userJoinedActiveList.map((active: activity, index) => {
                    let items = [];
                    active.isJoin = '1';
                    items.push(<List.Item arrow='horizontal'
                                          key={index * 2}
                                          onClick={this.goToDetail.bind(this, active)}>
                        <MyText style={{marginLeft: 10}}>{moment(active.started).format('MM月DD日')}</MyText>
                        <List.Item.Brief style={{paddingLeft: 10}}><MyText>{active.title}</MyText></List.Item.Brief>
                    </List.Item>);
                    return items;
                })}
                <Line height={20} color={'#f4f4f4'}/>
            </List>
        )
    };
    renderItem = (i) => {

        let item: activeItem = i.item;
        let activity: activity = item.activity;

        //onPress={Actions.activeDetail.bind(null, {item})}
        return (
            <TouchableOpacity>
                {/*月份*/}
                <View style={[activeStyles.listItem, activeStyles.header]}>
                    <MyText color={'#333'} fontSize={15}>{moment(activity.created).format('MM月DD日')}</MyText>
                </View>
                {/*内容*/}
                <View style={[activeStyles.listItem, activeStyles.item, activeStyles.content]}>
                    <View style={[commonStyles.flex1, commonStyles.flexColumn, {justifyContent: 'space-around'}]}>
                        <MyText color={'#333'} fontSize={20} fontWeight={'500'}
                                numberOfLines={1}>{activity.title}</MyText>
                        <MyText color={'#333'}
                                fontSize={15}>{`${moment(activity.started).format('A HH:mm')}至${moment(activity.ended).format('A HH:mm')}`}</MyText>
                    </View>
                    <Line/>
                </View>
                {/*地址*/}
                <View style={[activeStyles.listItem, activeStyles.item]}>
                    <MyText color={'#333'} fontSize={12}>{activity.address}</MyText>
                </View>
                <View style={{paddingLeft: 10, backgroundColor: '#fff'}}>
                    <Line type={'dashed'}/>
                </View>
                {/*成员*/}
                <View style={[activeStyles.listItem, activeStyles.item, commonStyles.flexRow]}>
                    <View style={[commonStyles.flex1, commonStyles.flexRow]}>
                        {/*活动成员*/}
                        {this.renderMembers(item.users)}
                    </View>
                    <TouchableOpacity onPress={this.joinOrLeaveActive.bind(this, item)}>
                        <View
                            style={[commonStyles.flexRow, groupStyles.joinBtn, item.isJoin === '1' ? groupStyles.isJoin : null]}>
                            <MyIcon name={item.isJoin === '0' ? 'icon-jia1' : 'icon-gou'}
                                    color={item.isJoin === '1' ? '#999' : '#000'} size={15}/>
                            <MyText fontSize={15} style={{marginLeft: 5}}
                                    color={item.isJoin === '1' ? '#999' : '#000'}>{item.isJoin === '1' ? '已加入' : '加入'}</MyText>
                        </View>
                    </TouchableOpacity>
                </View>
            </TouchableOpacity>
        )
    };

    render() {

        return (
            <View style={[commonStyles.container, commonStyles.relative]}>

                <View style={commonStyles.flex1}>
                    <FlatList data={this.props.active.list ? this.props.active.list.content : []}
                              extraData={this.state}
                              onRefresh={this.onRefresh}
                              refreshing={this.props.active.loading}
                              ListEmptyComponent={<NoActive/>}
                              renderItem={this.renderItem}
                              ItemSeparatorComponent={() => <Line height={10} color={'#f4f4f4'}/>}
                              ListHeaderComponent={this.renderListHeaderComponent}
                              keyExtractor={(item, index) => index}/>
                </View>
                <TouchableOpacity style={filterButton.position}
                                  onPress={Actions.activeFilter}>
                    <View style={[filterButton.container, commonStyles.centerVH, commonStyles.flexRow]}>
                        <MyIcon name='icon-shaixuan1' color='#fff' size={15}/>
                        <MyText color={'#fff'}>筛选</MyText>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}


export default connect(
    ({auth, active}) => ({auth, active})
)(ActiveList);